/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.vrangogym.beans.ctrl;

import edu.chl.vrangogym.beans.backing.RegisterBackingBean;
import edu.chl.vrangogym.persistence.entities.values.ContactInfo;
import edu.chl.vrangogym.persistence.entities.User;
import edu.chl.vrangogym.persistence.entities.enums.Permissions;
import edu.chl.vrangogym.persistence.entities.values.Address;
import edu.chl.vrangogym.persistence.impl.UserFacade;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

/**
 *
 * @author Anders
 */
@ManagedBean(name = "RegisterCtrl")
@RequestScoped
public class RegisterCtrlBean implements Serializable {

    @EJB
    private UserFacade userFacade;
    
    @ManagedProperty(value = "#{Register}")
    RegisterBackingBean registerBackingBean;

    public void setregisterBackingBean(RegisterBackingBean registerBackingBean) {
        this.registerBackingBean = registerBackingBean;
    }

    /** Creates a new instance of RegisterControllerBean */
    public RegisterCtrlBean() {
    }

    @PostConstruct
    public void postConstruct() {
    }

    /**
     * Tries to create a User based on form data
     * @param evt 
     */
    public void register(ActionEvent evt) {
        //Check if username is already taken
        boolean userNameTaken = (userFacade.find(registerBackingBean.getUsername())!=null);
        
        
        // Check if passwords match
        if (registerBackingBean.getPassword().equals(registerBackingBean.getPassword2()) && !userNameTaken) {
            // Set ContactInfo
            ContactInfo contactInfo = new ContactInfo();
            contactInfo.setFirstName(registerBackingBean.getFirstname());
            contactInfo.setLastName(registerBackingBean.getLastname());
            contactInfo.setEmail(registerBackingBean.getMail());
            contactInfo.setPhoneNumber(registerBackingBean.getPhone());
            contactInfo.setAddress(new Address(registerBackingBean.getStreet(), registerBackingBean.getZipCode(), registerBackingBean.getCity()));
            // Set User
            User user = new User(registerBackingBean.getUsername(),
                    registerBackingBean.getPassword(), contactInfo, 0, null, Permissions.ADMIN);
            // Create the new user
            userFacade.create(user);
        } else if (userNameTaken) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Användarnamnet är upptaget"));
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Lösenorden är olika"));
        }
    }
}
